package org.penguin.boot.security.entity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serial;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class PenguinUserDetails implements UserDetails {

    @Serial
    private static final long serialVersionUID = 1454740355871822223L;
    private final User user;

    public PenguinUserDetails(User user) {
        this.user = user;
    }

    /**
     * @return 用户权限信息
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getAuthorities(user.getRoles());
    }

    @Override
    public String getPassword() {
        return user == null ? null : user.getPassword();
    }

    @Override
    public String getUsername() {
        return user == null ? null : user.getEmail();
    }

    /**
     * @return 账户是否未过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return user != null && !user.isTokenExpired();
    }

    /**
     * @return 账户是否未被锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return user != null && user.isEnabled();
    }

    /**
     * @return 凭证（密码）是否未过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return user != null && !user.isTokenExpired();
    }

    /**
     * @return 账户是否启用
     */
    @Override
    public boolean isEnabled() {
        return user != null && user.isEnabled();
    }

    /**
     * 通过角色获取权限信息
     * @param roles
     * @return
     */
    private Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roles) {
        return getGrantedAuthorities(getPrivileges(roles));
    }

    private List<GrantedAuthority> getGrantedAuthorities(List<String> privileges) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }
        return authorities;
    }

    /**
     *
     * @param roles 角色
     * @return 角色下的所有权限(*__PRIVILEGE)及角色(ROLE_*)
     */
    private List<String> getPrivileges(Collection<Role> roles) {
        List<String> privileges = new ArrayList<>();
        List<Privilege> collection = new ArrayList<>();
        for (Role role : roles) {
            privileges.add(role.getName());
            collection.addAll(role.getPrivileges());
        }
        for (Privilege item : collection) {
            privileges.add(item.getName());
        }
        return privileges;
    }

    public String getSalt() {
        return user == null ? null : user.getSalt();
    }
}
